import React, { useEffect } from "react";
import { FilterArea, ProductList } from "@/components";
import styles from "./SearchPage.module.css";
import { useParams, useNavigate } from "react-router-dom";
import { getProductSearch } from "@/redux/productSearch/slice";
import { useSelector, useDispatch } from "@/redux/hooks";
import { Spin } from "antd";
import { MainLayout } from "@/layouts";


type MatchParams = {
  keywords: string;
};

export const SearchPage: React.FC = () => {
  // 获取参数
  const { keywords } = useParams<MatchParams>();
  // 获取redux里面的数据
  const loading = useSelector<boolean>((s) => s.productSearch.loading);
  const error = useSelector<string | null>((s) => s.productSearch.error);
  const pagination = useSelector((s) => s.productSearch.pagination);
  const productList = useSelector((s) => s.productSearch.data);

  const dispatch = useDispatch();
  const location = useNavigate();

  useEffect(() => {
    // 如果url变化 则取搜索
    dispatch(getProductSearch({ nextPage: 1, pageSize: 10, keywords }));
  }, [location]);

  const onPageChange = (nextPage, pageSize) =>{
    dispatch(getProductSearch({nextPage, pageSize, keywords}))
  }

  if (loading) {
    return (
      <Spin
        size="large"
        style={{
          marginTop: 200,
          marginBottom: 200,
          marginLeft: "auto",
          marginRight: "auto",
          width: "100%",
        }}
      />
    );
  }
  if (error) {
    return <div>网站出错：{error}</div>;
  }

  return (
    <MainLayout>
      <div className={styles["page-content"]}>
        {/* 分类过滤器 */}
        <div className={styles["product-list-container"]}>
          <FilterArea />
        </div>
        {/* 产品列表 */}
        <div className={styles["product-list-container"]}>
          <ProductList
            data={productList}
            paging={pagination}
            onPageChange={onPageChange}
          />
        </div>
      </div>
    </MainLayout>
  );
};
